package com.starblink.android.basic.sensorsdata.room.mana

import android.app.Application
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.starblink.android.basic.sensorsdata.room.config.DatabaseConfig
import com.starblink.android.basic.sensorsdata.room.database.SkTraceDataBase

//https://www.jianshu.com/p/243a862c5cfe
object SkTraceDatabaseManager {
    private val MIGRATIONS = arrayOf(Migration1)
    private lateinit var application: Application
    val db: SkTraceDataBase by lazy {
        Room.databaseBuilder(application.applicationContext, SkTraceDataBase::class.java, DatabaseConfig.spmDbName)
            .addCallback(CreatedCallBack)
//            .allowMainThreadQueries()
//            .addMigrations(*MIGRATIONS)
            .fallbackToDestructiveMigration()
            .build()
    }

    fun saveApplication(application: Application) {
        SkTraceDatabaseManager.application = application
    }

    private object CreatedCallBack : RoomDatabase.Callback() {
        override fun onCreate(db: SupportSQLiteDatabase) {
            //在新装app时会调用，调用时机为数据库build()之后，数据库升级时不调用此函数
            MIGRATIONS.map {
                it.migrate(db)
            }
        }
    }

    private object Migration1 : Migration(2, 3) {
        override fun migrate(database: SupportSQLiteDatabase) {
            // 数据库的升级语句 如插入什么字段/在原基础上做什么操作之类的
            // database.execSQL("")
            // database.execSQL("ALTER TABLE road_map_points add COLUMN txt_count INTEGER NOT NULL DEFAULT -1 ")
        }
    }
}